package com.sumer.psychology.sharing.domain.service;

import com.sumer.psychology.common.Assert;
import com.sumer.psychology.common.domain.model.AbstractDomainService;
import com.sumer.psychology.friend.domain.model.Member;
import com.sumer.psychology.friend.infrastructure.port.MemberTranslator;
import com.sumer.psychology.sharing.domain.model.Recommendation;
import com.sumer.psychology.sharing.domain.model.SharedResource;
import com.sumer.psychology.sharing.domain.model.SharedResourceRecommendedEvent;

/**
 * 推荐服务
 * <p/>
 * User: zhenguang.zhu
 * Date: 2014/9/12
 * Time: 9:44
 */
public class RecommendationService extends AbstractDomainService {
    private MemberTranslator memberTranslator;

    public RecommendationService(MemberTranslator memberTranslator) {
        this.memberTranslator = memberTranslator;
    }

    /**
     * 推荐一个资源给好友
     *
     * @param aSharedResource a resource
     * @param friendId friend id
     * @return recommendation
     */
    public Recommendation recommend(SharedResource aSharedResource, String friendId) {
        Member author = memberTranslator().toMember(aSharedResource.author());
        Member aFriend = memberTranslator().toMember(friendId);

        Assert.notNull(author, "作者不存在");
        Assert.notNull(aFriend, "好友不存在");
        Assert.isTrue(author.haveFriend(aFriend), "不是我的好友");

        Recommendation recommendation = new Recommendation(
                aSharedResource.sharedResourceId(),
                author.memberId(),
                aFriend.memberId());

        apply(new SharedResourceRecommendedEvent(
                recommendation.sharedResourceId(),
                recommendation.from(),
                recommendation.to()));

        return recommendation;
    }

    private MemberTranslator memberTranslator() {
        return memberTranslator;
    }
}
